﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace Details.API
{
    /// <summary>
    /// 创建令牌封装
    /// </summary>
    public static class CreateToKenway
    {
        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        public static IServiceCollection GetToken(this IServiceCollection services)
        {

            //授权认证（使用JWT）
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                // 私钥
                var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = "BeiJingBW",

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = "BeiJingBW",

                    // 验证是否过期
                    ValidateLifetime = true,

                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                };
            });



            //配置 AddSwaggerGen

            services.AddSwaggerGen(o =>
            {
                o.IncludeXmlComments(AppContext.BaseDirectory + "Details.API.xml", true);//接口注释

                // 显示 授权信息
                o.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme()
                {
                    Description = "添加JWT授权Token：Bearer Token值",
                    Name = "Authorization",
                    In = Microsoft.OpenApi.Models.ParameterLocation.Header,
                    Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                o.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.SecurityScheme,
                                    Id = "Bearer"
                                }
                            },
                            new string[]
                            {

                            }
                        }
                    });
            });
            return services;
        }
    }
}
